﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace C12_Ex03_Shaked_032675316_Itay_032511057
{
    public class ImageRandomRotateDecorator : ImageFormaterDecorator
    {
        public ImageRandomRotateDecorator(ImageFormaterDecorator i_ImageStringFormatter) : base(i_ImageStringFormatter)
        {
        }

        public ImageRandomRotateDecorator()
            : base()
        {
        }

        public override Image FormatImage(Image i_Image)
        {
            i_Image = base.FormatImage(i_Image);

            float angle = new Random().Next(-30, 30);
            int width = i_Image.Width;
            int height = i_Image.Height;
            Color backGroundColor = Color.White;
            PixelFormat pictureFormat = default(PixelFormat);
            if (backGroundColor == Color.Transparent)
            {
                pictureFormat = PixelFormat.Format32bppArgb;
            }
            else
            {
                pictureFormat = i_Image.PixelFormat;
            }

            pictureFormat = i_Image.PixelFormat;

            Bitmap tempImage = new Bitmap(width, height, pictureFormat);
            Graphics graphics = Graphics.FromImage(tempImage);
            graphics.Clear(backGroundColor);
            graphics.DrawImageUnscaled(i_Image, 1, 1);
            graphics.Dispose();

            GraphicsPath path = new GraphicsPath();
            path.AddRectangle(new RectangleF(0f, 0f, width, height));
            Matrix mtrx = new Matrix();
            
            mtrx.Rotate(angle);
            RectangleF rct = path.GetBounds(mtrx);
            Bitmap newImg = new Bitmap(Convert.ToInt32(rct.Width), Convert.ToInt32(rct.Height), pictureFormat);
            graphics = Graphics.FromImage(newImg);
            graphics.Clear(backGroundColor);
            graphics.TranslateTransform(-rct.X, -rct.Y);
            graphics.RotateTransform(angle);
            graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
            graphics.DrawImageUnscaled(tempImage, 0, 0);       
            graphics.Dispose();
            tempImage.Dispose();

            return (Image)newImg;  
        }
    }
}
